package com.icloud.cer.rest;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icloud.cer.rest.msg.AbsMsgObject;
import com.icloud.cer.rest.msg.MessageHeader;
import com.icloud.cer.rest.msg.MessageHolder;

public class ObjectClientEncoder extends ProtocolEncoderAdapter{

	
	private static final Logger log = LoggerFactory.getLogger(ObjectClientEncoder.class);

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		if (!(message instanceof MessageHolder)) {
			throw new RuntimeException("Error mina message, or mina handler config error.");
		}
		MessageHolder holder = (MessageHolder)message;
		if(!checkHolder(holder)) {
			log.error("holder is invalid.");
			return;
		}
		log.debug("encode:" + holder.getCommand());
		
		MessageHeader head = holder.getHead();
		byte[] headData = head.serialize();
		
		IoBuffer buf = IoBuffer.allocate(MessageHeader.BYTE_COUNT + head.getSize_());
		buf.setAutoExpand(true);
		buf.put(headData);
		AbsMsgObject body = holder.getValue();
		byte[] bodyData = body.serialize();
		buf.put(bodyData);
		buf.flip();
		out.write(buf);
		log.info("send message:" + buf);
	}
	
	private boolean checkHolder(MessageHolder holder) {
		if (holder.getCommand() == 0) {
			log.error("command is 0");
			return false;
		}
		return true;
	}

}
